#pragma once

#include <boost/asio.hpp>
#include <list>
#include <map>

#include "libdaq/backend/socket/socket_backend.h"

namespace libdaq {
namespace backend {
using TCPSocketMap = std::map<std::string, LockzhinerSocketBackend* >;
class LockzhinerTCPServer {
public:
    LockzhinerTCPServer(const std::string &ip_address, uint_least16_t port);
    ~LockzhinerTCPServer();

    std::vector<std::string> GetClientsIP() const;
    LockzhinerSocketBackend* GetClient(const std::string &ip);

    void StartAccept(int duration_ms = 1000, bool async = false, unsigned int client_count = 1);
    bool IsAcceptComplete();
    void DisconnectClient(const std::string &ip);

private:
    void AcceptorAccept();
    void HandleAccept(LockzhinerSocketBackend* socket, const boost::system::error_code &error);
    void HandleTimeout();

    unsigned int max_client_count_ = 1; // 最大连接个数
    boost::asio::io_context io_context_;
    boost::asio::steady_timer timeout_timer_; // 添加定时器成员
    std::atomic<bool> is_accepting_ = false;
    std::unique_ptr<boost::asio::ip::tcp::tcp::acceptor> acceptor_;
    std::unique_ptr<boost::asio::deadline_timer> accept_timer_ = nullptr;
    std::unique_ptr<boost::asio::detail::thread> accept_thread_ = nullptr;
    TCPSocketMap clients_{};
};
}
}
